﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Claims;
using AppSocketModel; 
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;

namespace BCGPSRESTful
{
    /// <summary>
    /// Token扩展
    /// </summary>
    public static class TokenExtension
    {
        internal static readonly string Issuer = "http://api.bc-gps.com/";
        internal static readonly string Audience = "BlackCoffice";
        internal static readonly SymmetricSecurityKey SecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("BlackCoffice@bc-gps"));

        /// <summary>
        /// 生成访问令牌
        /// </summary>
        /// <param name="accountDto">账户</param>
        /// <param name="expiration">有效期</param>
        /// <param name="accountRole">登录角色</param>
        /// <returns></returns>
        public static string GenerateToken(this AccountDto accountDto, TimeSpan expiration, AccountRole  accountRole)
        { 
            List<Claim> claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name,"AccountId:"+accountDto.AccountId),
                new Claim(ClaimTypes.Role, accountRole.ToString())
            };
            var now = DateTime.UtcNow;
            var sc = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken(Issuer, Audience, claims, now, now.Add(expiration), sc);

            return new JwtSecurityTokenHandler().WriteToken(jwt);

        }


        /// <summary>
        /// 生成访问令牌
        /// </summary>
        /// <param name="accountDto">账户</param>
        /// <param name="expiration">有效期</param>
        /// <param name="accountRole">账户角色</param>
        /// <returns></returns>
        public static string GenerateToken(this SystemAccountDto accountDto, TimeSpan expiration, AccountRole  accountRole)
        {
            List<Claim> claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name,"AccountId:"+accountDto.AccountId),
                new Claim(ClaimTypes.Role, accountRole.ToString())
            };
            var now = DateTime.UtcNow;
            var sc = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken(Issuer, Audience, claims, now, now.Add(expiration), sc);

            return new JwtSecurityTokenHandler().WriteToken(jwt);

        }
    }
}
